package com.mioto.ld.communication.websocket;

import cn.hutool.json.JSONUtil;
import com.google.gson.*;
import com.mioto.ld.communication.websocket.model.ReceiveCmdEnum;
import com.mioto.ld.communication.websocket.model.WsAttributeSetBody;
import com.mioto.ld.communication.websocket.model.WsDeviceCloseBody;
import com.mioto.ld.communication.websocket.model.WsMessageBody;

import java.lang.reflect.Type;

/**
 * @author mioto-qinxj
 * @date 2024/5/16
 * @desc
 */
public class MessageBodyDeserializer implements JsonDeserializer<WsMessageBody> {
    String text;
    public MessageBodyDeserializer(String text){
        this.text = text;
    }

    @Override
    public WsMessageBody deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        JsonObject jsonObj = jsonElement.getAsJsonObject();
        Integer cmd = JSONUtil.parseObj(text).getInt("cmd");
        Class clazz = ReceiveCmdEnum.getBodyConvertBean(cmd);
        if (clazz == WsAttributeSetBody.class) {
            WsAttributeSetBody body = new WsAttributeSetBody();
            body.setSn(jsonObj.get("sn").getAsString());
            jsonObj.remove("sn");
            body.setAttributes(jsonObj.getAsJsonObject());
            return body;
        }else if (clazz == WsDeviceCloseBody.class){
            WsDeviceCloseBody body = new WsDeviceCloseBody();
            body.setSn(jsonObj.get("sn").getAsString());
            body.setPower(jsonObj.get("power").getAsInt());
            return body;
        }
        return null;
    }
}
